<template>
  <div class="ai-legal-qa">
    <div class="qa-header">
      <h1>AI法律智能助手</h1>
      <p>24小时在线的专业法律咨询，为您提供即时法律解答</p>
    </div>

    <div class="qa-container">
      <!-- 聊天区域 -->
      <div class="chat-area">
        <div class="messages" ref="messagesRef">
          <div v-for="(message, index) in messages" :key="index" :class="['message', message.type]">
            <div class="message-avatar">
              <el-avatar v-if="message.type === 'ai'" :size="32" :src="aiAvatar" />
              <el-avatar v-else :size="32" :src="userStore.user?.avatar" />
            </div>
            <div class="message-content">
              <div class="message-bubble">
                <div v-if="message.type === 'ai'" class="ai-header">
                  <span class="ai-name">法律助手</span>
                  <el-tag size="small" type="success">AI</el-tag>
                </div>
                <div class="message-text" v-html="formatMessage(message.content)"></div>
                <div v-if="message.type === 'ai'" class="message-actions">
                  <el-button size="small" @click="copyToClipboard(message.content)">
                    <el-icon><DocumentCopy /></el-icon>复制
                  </el-button>
                  <el-button size="small" @click="rateResponse(index, 'helpful')">
                    <el-icon><Star /></el-icon>有帮助
                  </el-button>
                </div>
              </div>
              <div class="message-time">{{ message.time }}</div>
            </div>
          </div>

          <!-- 输入区域 -->
          <div class="input-area">
            <div class="quick-questions" v-if="messages.length === 0">
              <h3>常见问题类型</h3>
              <div class="quick-buttons">
                <el-button
                  v-for="question in quickQuestions"
                  :key="question.text"
                  @click="sendQuickQuestion(question)"
                  class="quick-btn"
                >
                  {{ question.text }}
                </el-button>
              </div>
            </div>

            <div class="input-wrapper">
              <el-input
                v-model="userInput"
                type="textarea"
                :rows="3"
                placeholder="请输入您的法律问题..."
                :disabled="isLoading"
                @keydown.enter.exact.prevent="sendMessage"
                resize="none"
              />
              <div class="input-actions">
                <el-button
                  type="primary"
                  @click="sendMessage"
                  :loading="isLoading"
                  :disabled="!userInput.trim()"
                >
                  <el-icon><Promotion /></el-icon>
                  {{ isLoading ? '思考中...' : '发送' }}
                </el-button>
                <el-button @click="clearChat">
                  <el-icon><Delete /></el-icon>
                  清空对话
                </el-button>
              </div>
            </div>

            <div class="disclaimer">
              <el-alert
                title="免责声明"
                type="info"
                :closable="false"
                description="AI回答仅供参考，不构成正式法律意见。如需正式法律意见，请咨询专业律师。"
                show-icon
              />
            </div>
          </div>
        </div>
      </div>

      <!-- 侧边栏 -->
      <div class="sidebar">
        <div class="sidebar-section">
          <h3>功能特点</h3>
          <ul class="feature-list">
            <li>
              <el-icon><Clock /></el-icon> 24小时在线
            </li>
            <li>
              <el-icon><Collection /></el-icon> 法律知识库
            </li>
            <li>
              <el-icon><Lock /></el-icon> 隐私保护
            </li>
            <li>
              <el-icon><Freeze /></el-icon> 免费使用
            </li>
          </ul>
        </div>

        <div class="sidebar-section">
          <h3>支持的法律领域</h3>
          <div class="law-areas">
            <el-tag v-for="area in lawAreas" :key="area" class="area-tag">
              {{ area }}
            </el-tag>
          </div>
        </div>

        <div class="sidebar-section">
          <h3>转接人工服务</h3>
          <p>如果AI无法解决您的问题</p>
          <el-button type="warning" @click="redirectToLawyer">
            <el-icon><User /></el-icon>
            联系专业律师
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { userInfoStore } from '@/stores/userinfo'
import { ElMessage } from 'element-plus'
import {
  DocumentCopy,
  Star,
  Promotion,
  Delete,
  Clock,
  Collection,
  Lock,
  Freeze,
  User,
} from '@element-plus/icons-vue'

const router = useRouter()
const userStore = userInfoStore()
const messagesRef = ref(null)

// 数据
const userInput = ref('')
const isLoading = ref(false)
const messages = ref([])
const aiAvatar = '/ai-avatar.png' // AI头像路径

// 快速问题
const quickQuestions = reactive([
  { text: '劳动合同纠纷', type: 'labor' },
  { text: '婚姻家庭问题', type: 'family' },
  { text: '房产纠纷', type: 'property' },
  { text: '债务纠纷', type: 'debt' },
  { text: '交通事故赔偿', type: 'traffic' },
  { text: '消费者权益', type: 'consumer' },
])

// 法律领域
const lawAreas = reactive([
  '民事纠纷',
  '刑事法律',
  '行政法',
  '公司法',
  '合同法',
  '知识产权',
  '劳动法',
  '婚姻法',
  '继承法',
  '侵权责任',
])

// 发送消息
const sendMessage = async () => {
  if (!userInput.value.trim() || isLoading.value) return

  const userMessage = {
    type: 'user',
    content: userInput.value,
    time: new Date().toLocaleTimeString(),
  }

  messages.value.push(userMessage)
  const question = userInput.value
  userInput.value = ''
  isLoading.value = true

  // 滚动到底部
  await nextTick()
  scrollToBottom()

  try {
    // 调用AI问答API
    const response = await api.ai.askQuestion({
      question: question,
      userId: userStore.user?.id,
      context: messages.value.slice(-10), // 最近10条作为上下文
    })

    const aiMessage = {
      type: 'ai',
      content: response.data.answer,
      time: new Date().toLocaleTimeString(),
      references: response.data.references || [],
    }

    messages.value.push(aiMessage)
  } catch (error) {
    console.error('AI问答失败:', error)
    const errorMessage = {
      type: 'ai',
      content:
        '抱歉，我现在遇到了一些技术问题，请稍后再试。您也可以直接联系我们的专业律师获取帮助。',
      time: new Date().toLocaleTimeString(),
    }
    messages.value.push(errorMessage)
  } finally {
    isLoading.value = false
    await nextTick()
    scrollToBottom()
  }
}

// 发送快速问题
const sendQuickQuestion = (question) => {
  userInput.value = `关于${question.text}的法律咨询：`
}

// 复制到剪贴板
const copyToClipboard = async (text) => {
  try {
    await navigator.clipboard.writeText(text)
    ElMessage.success('已复制到剪贴板')
  } catch (err) {
    console.error('复制失败:', err)
    ElMessage.error('复制失败')
  }
}

// 评价回复
const rateResponse = (index, rating) => {
  // 发送评价到后端
  console.log(`评价消息 ${index}: ${rating}`)
  ElMessage.success('感谢您的反馈！')
}

// 清空对话
const clearChat = () => {
  messages.value = []
}

// 滚动到底部
const scrollToBottom = () => {
  if (messagesRef.value) {
    messagesRef.value.scrollTop = messagesRef.value.scrollHeight
  }
}

// 格式化消息内容
const formatMessage = (content) => {
  // 简单的格式化处理，可以添加更多格式化逻辑
  return content.replace(/\n/g, '<br>')
}

// 转接到律师
const redirectToLawyer = () => {
  router.push('/lawyers')
}

// 初始化欢迎消息
onMounted(() => {
  const welcomeMessage = {
    type: 'ai',
    content: '您好！我是法律智能助手，可以为您解答各种法律问题。请问您需要咨询什么法律问题？',
    time: new Date().toLocaleTimeString(),
  }
  messages.value.push(welcomeMessage)
})
</script>

<style scoped>
.ai-legal-qa {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.qa-header {
  text-align: center;
  margin-bottom: 30px;
}

.qa-header h1 {
  color: #003366;
  margin-bottom: 10px;
}

.qa-header p {
  color: #666;
  font-size: 16px;
}

.qa-container {
  display: grid;
  grid-template-columns: 1fr 300px;
  gap: 20px;
  height: 70vh;
}

.chat-area {
  display: flex;
  flex-direction: column;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.messages {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.message {
  display: flex;
  gap: 12px;
}

.message.user {
  flex-direction: row-reverse;
}

.message-avatar {
  flex-shrink: 0;
}

.message-content {
  flex: 1;
  max-width: 70%;
}

.message-bubble {
  padding: 12px 16px;
  border-radius: 12px;
  background: #f5f7fa;
}

.message.user .message-bubble {
  background: #003366;
  color: white;
}

.ai-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.ai-name {
  font-weight: bold;
  color: #003366;
}

.message-text {
  line-height: 1.6;
}

.message-time {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
  text-align: right;
}

.message.user .message-time {
  text-align: left;
}

.message-actions {
  margin-top: 8px;
  display: flex;
  gap: 8px;
}

.input-area {
  border-top: 1px solid #eee;
  padding: 20px;
}

.quick-questions {
  margin-bottom: 20px;
}

.quick-questions h3 {
  margin-bottom: 12px;
  color: #003366;
}

.quick-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.quick-btn {
  font-size: 12px;
}

.input-wrapper {
  margin-bottom: 16px;
}

.input-actions {
  display: flex;
  gap: 8px;
  margin-top: 12px;
  justify-content: flex-end;
}

.disclaimer {
  margin-top: 16px;
}

.sidebar {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.sidebar-section {
  background: white;
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.sidebar-section h3 {
  color: #003366;
  margin-bottom: 12px;
}

.feature-list {
  list-style: none;
  padding: 0;
}

.feature-list li {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 0;
  color: #666;
}

.law-areas {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.area-tag {
  margin: 2px;
}
</style>
